<style scoped>
</style>

<template>

  <div>

    <Modal
      v-model="IsModalShow"
      :title="modalFormTitle"
      :mask-closable="false"
      @on-cancel="cancel"
      width="600"
    >
      <Form
        ref="modalForm"
        :model="modalForm"
        :label-width="80"
        value=true
        style="padding: 3px 60px"
      >
        <Form-item
          label="角色名称"
          prop="roleName"
          :rules="{required: true, message: '必填',min:1,max:10, trigger:'blur',type:'string'}"
        >
          <Input v-model="modalForm.roleName"></Input>
        </Form-item>
     <!--   <Form-item
          label="所属部门"
          prop="depCascader"
          :rules="{required: true, message: '必选', trigger:'change', type:'array'}"
        >
          <Cascader
            :data="deptCascader"
            v-model="modalForm.depCascader"
            :filterable="true"
            change-on-select
            transfer
            placeholder="选择部门"
          ></Cascader>
        </Form-item>-->
        <Form-item label="备注">
          <Input v-model="modalForm.remark"></Input>
        </Form-item>
        <Row>
          <Col :span="24">
          <Tree
            ref="menuTree"
            :data="menuTree"
            show-checkbox
          ></Tree>
          </Col>
        <!--<Col :span="12">
          <Tree
            ref="deptTree"
            :data="deptTree"
            show-checkbox
            check-strictly
          ></Tree>-->
          </Col>
        </Row>

      </Form>
      <div slot="footer">
        <Button
          type="default"
          @click="cancel"
        >关闭</Button>
        <Button
          type="primary"
          :loading="modalForm_loading"
          @click="saveForm('modalForm')"
        >保存</Button>
      </div>
    </Modal>
  </div>

</template>

<script>
import {
  saveRole,
  updateRole,
  getRoleInfo,
  getMenuList
} from "@/api/system";
export default {
  props: {
    parentForm: {
      type: Object,
      default: function() {
        return {
          Id: "",
          roleName: ""
        };
      }
    },
    modalShow: {
      type: Boolean,
      default: true
    },
    modalFormTitle: {
      type: String,
      default: "添加角色"
    }
  },
  data() {
    return {
      IsModalShow: false,
      roleId: "",
      modalForm: {},
      modalForm_loading: false,
      menuTree: [],
      // deptTree: [],
      // deptCascader: [],
      // depCascaderValue:[]
    };
  },
  watch: {
    modalShow(curVal, oldVal) {
      this.IsModalShow = curVal;
      if (curVal) {
        this.roleId = this.parentForm.roleId;
        this.getRoleInfo();
        
      }
    }
  },
  mounted() {},
  methods: {
    async getRoleInfo() {
      let menuRes = await getMenuList();
      // let deptRes = await getDeptCascader();
      if (this.modalFormTitle == "修改角色") {
        let roleRes = await getRoleInfo(this.roleId);
        if (menuRes.code == 0 &&  roleRes.code == 0) {
          let menuTreeData = menuRes.data;
          // let deptTreeData = deptRes.data;
          // this.deptCascader = deptRes.data;
          let role = roleRes.data;
          let menuIdList = role.menuIdList;
          // let deptIdList = role.deptIdList;

          // if (role.depCascader) {
          //   role.depCascader = role.depCascader + "," + role.deptId;
          //   role.depCascader = role.depCascader
          //     .split(",")
          //     .map(val => parseInt(val));
          // } else {
          //   role.depCascader = [];
          // }

          this.menuTree = this.formatMenuTree(menuTreeData, menuIdList);
          //this.deptTree = this.formatDeptTree(deptTreeData, deptIdList);
          var vm = this;
           setTimeout(function(){  vm.modalForm = role;}, 100);
         
        }
      } else {
        if (menuRes.code == 0) {
          let menuTreeData = menuRes.data;
          // let deptTreeData = deptRes.data;
          // this.deptCascader = deptRes.data;
          let role = this.parentForm;
          let menuIdList = role.menuIdList;
          // let deptIdList = role.deptIdList;
          // role.depCascader = [];

          this.menuTree = this.formatMenuTree(menuTreeData, menuIdList);
          //this.deptTree = this.formatDeptTree(deptTreeData, deptIdList);
          this.modalForm = JSON.parse(JSON.stringify(role));
        }
      }
    },
    formatMenuTree(menus = [], menuIdList = []) {
      var resMenuTree = [];
      menus.forEach((item, i) => {
        let resItem = {};
        resItem.title = item.name;
        resItem.menuId = item.menuId;
        if (item.children && item.children.length > 0) {
          resItem.children = this.formatMenuTree(item.children, menuIdList);
        } else {
          menuIdList.find((id, index) => {
            if (item.menuId == id) {
              resItem.checked = true;
            }
          });
        }
        resMenuTree.push(resItem);
      });
      return resMenuTree;
    },
    formatDeptTree(depts = [], deptIdList = []) {
      var resDeptTree = [];
      depts.forEach((item, i) => {
        let resItem = {};
        resItem.title = item.label;
        resItem.deptId = item.value;
        resItem.expand = true;
        deptIdList.find((id, index) => {
          if (item.value == id) {
            resItem.checked = true;
          }
        });
        if (item.children && item.children.length > 0) {
          resItem.children = this.formatDeptTree(item.children, deptIdList);
        }
        resDeptTree.push(resItem);
      });
      return resDeptTree;
    },
    cancel() {
      this.$emit("listenModalForm");
    },
    saveForm(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          this.modalForm_loading = true;
          let params = {
            roleId: this.modalForm.roleId,
            roleName: this.modalForm.roleName,
            // deptId: this.modalForm.depCascader[
            //   this.modalForm.depCascader.length - 1
            // ],
            menuIdList: this.$refs["menuTree"]
              .getCheckedAndIndeterminateNodes()
              .map(val => val.menuId),
            // deptIdList: this.$refs["deptTree"]
            //   .getCheckedNodes()
            //   .map(val => val.deptId),
            remark: this.modalForm.remark,
            createTime:this.modalForm.createTime
          };

          try {
            let result;
            if (params.roleId) {
              result = await updateRole(params);
            } else {
              result = await saveRole(params);
            }

            if (result.code == 0) {
              this.$emit("listenModalForm");
              this.$emit("refreshTableList");
            }
          } catch (err) {
            console.log(err);
            this.$Message.error("服务器异常，稍后再试");
          }
          this.modalForm_loading = false;
        } else {
          this.$Message.error("表单验证失败!");
        }
      });
    }
  }
};
</script>
